﻿#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define MaxWordLength 50 //单词的最大长度
#define MaxWordsNum 1000 //最多有多少个单词
//打印名字和学号的函数
void PrintInfo(void)
{
	printf("My Name is : %s\n", "ZHANG");
	printf("My Student ID is : %s\n", "22156558");
}

int ArrayEqual(char Word1[MaxWordLength], char Word2[MaxWordLength])
{
	//返回值1表示相等，0表示不等
	int _RtnVal = 1;
	for (int i = 0; i < MaxWordLength; i++)
	{
		if (Word1[i] != Word2[i])
		{
			_RtnVal = 0;
			return _RtnVal;
		}
	}
	return _RtnVal;
}

int Count(char Words[MaxWordsNum][MaxWordLength])
{
	char DistinctWords[MaxWordsNum][MaxWordLength] = {0}; 
    //去除重复后的Words，第一维为单词的个数，第二维保存单词
	int WordsCount[MaxWordsNum] = {0};					  
    // Words数组中单词出现的次数
	for (int i = 0; i < MaxWordsNum; i++)
	{
		if (Words[i][0] != 0)
		{
			int IsExisted = 0; //该单词是否已经存在
			//不为0，存在单词
			for (int j = 0; j < MaxWordsNum; j++)
			{
				//判断该单词是否在DistinctWords中
				if (ArrayEqual(Words[i], DistinctWords[j]))
				{
					//					printf("Equal");
					WordsCount[j]++;
					IsExisted = 1;
				}
			}

			if (IsExisted == 0)
			{
				//该单词不存在
				//找到第一个空位
				for (int j1 = 0; j1 < MaxWordsNum; j1++)
				{
					if (DistinctWords[j1][0] == 0)
					{
						//将单词加入DistinctWords中
						for (int k = 0; k < MaxWordLength; k++)
						{
							DistinctWords[j1][k] = Words[i][k];
						}
						WordsCount[j1] = 1;
						break;
					}
				}
			}
		}
	}
	//按从大到小的顺序排序,冒泡排序
	char _TmpWord;
	int _TmpInt;
	for (int i = 0; i < MaxWordsNum; i++)
	{
		for (int j = 0; j < MaxWordsNum; j++)
		{
			if (WordsCount[i] > WordsCount[j])
			{
				//交换
				_TmpInt = WordsCount[i];
				WordsCount[i] = WordsCount[j];
				WordsCount[j] = _TmpInt;
				for (int k = 0; k < MaxWordLength; k++)
				{
					_TmpWord = DistinctWords[i][k];
					DistinctWords[i][k] = DistinctWords[j][k];
					DistinctWords[j][k] = _TmpWord;
				}
			}
		}
	}

	printf("The word frequency is described as follows:\n");
	//打印结果
	for (int i = 0; i < 10; i++)
	{
		if (DistinctWords[i][0] != 0)
		{
			printf("%s:%d\n", DistinctWords[i], WordsCount[i]);
		}
	}

	return 0;
}

void main()
{
	PrintInfo();

	char Words[MaxWordsNum][MaxWordLength] = {0}; //第一维为单词的个数，第二位保存单词

	FILE *MyFile;
	MyFile = fopen("a.txt", "r");
	int len;
	char c;

	if (MyFile == NULL)
	{
		perror("打开文件时发生错误");
		return (-1);
	}
	int i = 0, j = 0;

	do
	{
		c = fgetc(MyFile);
//		printf("%c", c);
		if (c == ' ' || c == ',' || c == '.' || c == '\n')
		{
			//读进来的字符不是空格，逗号，句号，回车
			i++;
			j = 0;
		}
		else
		{
			Words[i][j] = c;
			j++;
		}
	}
	while (!feof(MyFile) && i < MaxWordsNum);

	fclose(MyFile);

	for (int k = 0; k < MaxWordsNum; k++)
	{
		if (Words[k][0] != 0)
		{
			//			printf("%s\n", Words[k]);
		}
	}

	//开始统计词频
	Count(Words);
}
